package cn.kuick.iplocation.entity;



import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;

/*
用于单元测试一些实体类的get set方法不能执行
实体类的参数类型需要放在paramTypeMap里面，只会执行匹配的参数类型
传入类名.class，自动执行该类的参数的get set方法
*/

public class EntityCoverImplement {
    private static Map paramTypeMap;

    static {
        paramTypeMap = new HashMap();

        paramTypeMap.put("int", 1);
        paramTypeMap.put("class java.lang.String", "huang");
        paramTypeMap.put("class java.util.Date", "2016-06-13 20:15:31");
        paramTypeMap.put("class java.lang.Integer", 1);

    }

    public static void callGetAndSetMethod(Class cHandle) throws IllegalAccessException, InstantiationException {
        Object obj;
        obj = cHandle.newInstance();

        Field[] fields = cHandle.getDeclaredFields();

        for(int i=0; i<fields.length; i++){
            String paramName = fields[i].getName();
            paramName = titleCapital(paramName);

            System.out.print(fields[i].getName()+ "     ");
            System.out.println(fields[i].getType());

            Method method = null;
            try {
                method = cHandle.getDeclaredMethod("set"+paramName, fields[i].getType());
            } catch (NoSuchMethodException e) {

            }

            if(method != null) {
                try {
                    method.invoke(obj, paramTypeMap.get(fields[i].getType().toString()));
                } catch (IllegalArgumentException e) {
                } catch (IllegalAccessException e) {
                } catch (InvocationTargetException e) {
                }
            }

            try {
                method = cHandle.getDeclaredMethod("get"+paramName);
            } catch (NoSuchMethodException e) {
            }

            if(method != null) {
                try {
                    method.invoke(obj);
                } catch (InvocationTargetException e) {
                }
            }
        }
    }

    private static String titleCapital(String oringinStr){
        char titleChar = oringinStr.charAt(0);
        titleChar = (char)((int)titleChar - 32);

        oringinStr = oringinStr.substring(1);
        oringinStr = titleChar + oringinStr;

        return oringinStr;
    }
}
